<template>
  <div class="app-container">
    <el-form ref="ruleForm" :rules="rules" :model="form" label-width="120px">
      <el-form-item label="单位名称" prop="name" >
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>

      <el-form-item style="text-align: center;">
        <el-button :loading="buttonLoading" type="primary" @click="onSubmit('ruleForm')">确认</el-button>
        <el-button @click="onCancel">关闭</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      buttonLoading: false,
      options: [{
        value: 1,
        label: '职能单位'
      }, {
        value: 2,
        label: '管理区'
      }],
      form: {},
      rules: {
        name: [
          { required: true, message: '请输入单位名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      }
    }
  },
  created() {

  },
  methods: {
    onSubmit(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          request({
            url: '/api/institution/addInstitution',
            method: 'post',
            data: this.form
          }).then((res) => {
            this.buttonLoading = false;
            this.$message(res.resultCodeDesc)
            if (res.resultCode === '200') {
              this.$emit('refresh');
              this.$emit('closeDialog', false);
            }
          }).catch(_ => {
            this.buttonLoading = false;
          })
        } else {
          this.$message({
            message: '表单验证失败',
            type: 'warning'
          })

          return false;
        }
      });
    },
    onCancel() {
      this.$emit('closeDialog', false);
    }
  }
}
</script>

<style scoped>

</style>
